<?php
/**
*+-------微信用户接入控制器--------+
*+-------------------------------------------------+
*-------对于微信用户接入的控制处理
*+-------------------------------------------------+
*+-@author susy.liang <liangling@ilongyuan.com.cn>-+
*+-------------------------------------------------+
*/
namespace Auth\Event;

class WeixinEvent extends PublicEvent {
	/**
	*成员变量的初始化
	*/
	protected function _initialize(){
		parent::_initialize();
		$this->params 	= 	C('thirdParty.weixin');
		$this->appId 	= 	$this->params['appId'];
		$this->appKey 	= 	$this->params['appKey'];
	}

	/**
	*回调
	*/
	 public function callBack($param=array()){
	 	if($param['state'] && $param['code']){//code的回调
   			$state = session('state');
   			if($state != $param['state']){
   				echo 'state参数不合法';
   				exit();
   			}
   			
   			$res = $this->getToken($param['code']);
            if($res === false){
               echo '获取用户token失败';
               exit();
            }else{
               $user = $this->getUser($res['token'], $res['openid']);
               //TODO:add user
               exit();
            }

   		}else{
            $this->error('参数错误：state&code不能为空');
        }
	 }


	/**
	*获取授权 authorize code
	*@param string $redirectUrl 回调的地址
	*@return boolean
	*/
	public function getCode($redirectUrl=''){
		if(empty($redirectUrl))
			return false;
		$redirectUrl = urlencode($redirectUrl);

		$state = md5(uniqid(time(), true));
		session('state', $state);

		$requestParam = array(
						'appid'=>$this->appId,
						'redirect_uri'=>$redirectUrl,
						'response_type'=>'code',
						'scope'=>$this->params['scope'],
						'state'=>$state,
			);
		$this->doHttp($this->params['codeApi'], $requestParam);

		return true;
	}

	/**
	*获取授权 token
	*@param string $authCode 授权码
	*/
	public function getToken($authCode=''){
		if(empty($authCode) )
			return false;

		$requestParam = array(
				'appid'=>$this->appId,
				'secret'=>$this->appKey,
				'code'=>$code,
				'grant_type'=>'authorization_code',
			);
		$res = $this->doHttp($this->params['tokenApi'], $requestParam);
		if($res['access_token']){
			$result = array(
					'token'=>$res['access_token'],
					'openid'=>$res['openid'],
				);
			return $result;
		}else{
			return false;
		}
	}

	/**
	*根据token获取用户基本信息
	*如昵称
	*/
	public function getUser($token='', $openid=''){
		if(empty($token) || empty($openid))
			return false;

		$requestParam = array(
					'access_token'=>$token,
					'openid'=>$openid,
			);
		$res = $this->doHttp($this->params['userApi'], $requestParam);
		if($res['openid']){
			$user = array(
					'openid'=>$res['openid'],
					'nickname'=>$res['nickname'],
					'avatar'=>$res['headimgurl'],
				);
			return $user;
		}else{
			return false;
		}
	}

}